package org.ktpro.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.ktpro.shortlink.admin.common.biz.user.UserContext;
import org.ktpro.shortlink.admin.common.biz.user.UserInfoDTO;
import org.ktpro.shortlink.admin.common.convention.exception.ClientException;
import org.ktpro.shortlink.admin.common.enums.UserErrorCodeEnum;
import org.ktpro.shortlink.admin.dao.entity.UserDO;
import org.ktpro.shortlink.admin.dao.mapper.UserMapper;
import org.ktpro.shortlink.admin.dto.req.UserLoginReqDTO;
import org.ktpro.shortlink.admin.dto.req.UserRegisterReqDTO;
import org.ktpro.shortlink.admin.dto.req.UserUpdateReqDTO;
import org.ktpro.shortlink.admin.dto.resp.UserLoginRespDTO;
import org.ktpro.shortlink.admin.dto.resp.UserRespDTO;
import org.ktpro.shortlink.admin.service.GroupService;
import org.ktpro.shortlink.admin.service.UserService;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static org.ktpro.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static org.ktpro.shortlink.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
import static org.ktpro.shortlink.admin.common.enums.UserErrorCodeEnum.*;

/**
 * 用户接口实现层
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    //构造器注入布隆过滤器
    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;

    // 新用户注册信息文件路径
    private static final String FILE_PATH = "register_user_info.txt";

    //注入redisson客户端，使用它的分布式锁
    private final RedissonClient redissonClient;

    private final StringRedisTemplate redisTemplate;

    private final GroupService groupService;

    /**
     * 根据用户名查询用户信息
     */
    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username);
        UserDO userDO = baseMapper.selectOne(queryWrapper);

//        使用封装的客户端错误异常
        if (userDO == null) throw new ClientException(UserErrorCodeEnum.USER_NULL);

        UserRespDTO userRespDTO = new UserRespDTO();
        BeanUtils.copyProperties(userDO, userRespDTO);

        return userRespDTO;
    }

    /**
     * 查询用户名是否存在
     */
    public Boolean hasUsername(String username) {
        return userRegisterCachePenetrationBloomFilter.contains(username);
    }

    /**
     * 注册用户
     */
    public void register(UserRegisterReqDTO userReqParam) {
        //用户名是否已存在
        if (hasUsername(userReqParam.getUsername())) {
            throw new ClientException(USER_NAME_EXIST);
        }

        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + userReqParam.getUsername());
        if (!lock.tryLock()) {
            throw new ClientException(USER_NAME_EXIST);
        }
        try {
            int inserted = baseMapper.insert(BeanUtil.toBean(userReqParam, UserDO.class));
            if (inserted < 1) {
                throw new ClientException(USER_SAVE_ERROR);
            }
            userRegisterCachePenetrationBloomFilter.add(userReqParam.getUsername());
            try {
                groupService.saveGroup("默认分组");
            } catch (Exception e) {
                log.warn("用户注册时创建默认分组失败");
            }

            // 获取当前时间并格式化
            String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            // 构建用户信息字符串
            String userInfo = String.format("%-10s | %-20s | %-13s | %-10s | %s",
                userReqParam.getUsername(),
                userReqParam.getMail(),
                userReqParam.getPhone(),
                userReqParam.getRealName(),
                currentTime);

            // 写入到txt文件
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_PATH, true))) {
                writer.write(userInfo);
                writer.newLine();
            } catch (IOException e) {
                // 处理文件写入异常
                log.error("写入注册用户信息到文件失败", e);
            }
        } catch (DuplicateKeyException ex) {
            throw new ClientException(USER_EXIST);
        } finally {
            lock.unlock();
        }
    }

    /**
     * 根据用户名修改用户信息
     *
     * @param requestParam 请求参数
     */
    public void update(UserUpdateReqDTO requestParam) {
        if (!Objects.equals(requestParam.getUsername(), UserContext.getUsername())) {
            throw new ClientException("当前登录用户修改请求异常");
        }
        LambdaQueryWrapper<UserDO> updateWq = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername());
        baseMapper.update(BeanUtil.toBean(requestParam, UserDO.class), updateWq);
    }

    /**
     * 用户登录接口
     */
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {

        UserContext.setUser(new UserInfoDTO(UUID.randomUUID().toString(), requestParam.getUsername(), requestParam.getUsername() + "real"));

        //1. 验证用户名和密码是否存在
        LambdaQueryWrapper<UserDO> query = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword())
                .eq(UserDO::getDelFlag, 0);//未注销的用户
        UserDO userDO = baseMapper.selectOne(query);

        if (userDO == null) throw new ClientException(USER_NULL);  //用户不存在

        Map<Object, Object> hasLoginMap = redisTemplate.opsForHash().entries(USER_LOGIN_KEY + requestParam.getUsername());
        if (CollUtil.isNotEmpty(hasLoginMap)) {
            //用户如果再次请求登录接口，则对用户token进行续期
            redisTemplate.expire(USER_LOGIN_KEY + userDO.getUsername(), 30L, TimeUnit.MINUTES);
            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录错误"));
            return new UserLoginRespDTO(token);
        }
        //2. 生成token (UUID)
        String tokenKey = IdUtil.simpleUUID();

        //保证不重复登录，需要用hash结构存一下用户名和登录凭证的关系到redis
        /**
         * hash
         *      key: login_用户名
         *      value:
         *          key:token
         *          value:JSON（用户信息userdo）
         */
        redisTemplate.opsForHash().put(USER_LOGIN_KEY + userDO.getUsername(), tokenKey, JSON.toJSONString(userDO));
        redisTemplate.expire(USER_LOGIN_KEY + userDO.getUsername(), 30L, TimeUnit.MINUTES);

        return new UserLoginRespDTO(tokenKey);
    }

    /**
     * 检查用户是否登录
     */
    public Boolean checkLogin(String username, String token) {
        return redisTemplate.opsForHash().get(USER_LOGIN_KEY + username, token) != null;
    }

    /**
     * 用户登出，删除redis token
     */
    public void logout(String username, String token) {
        if (checkLogin(username, token)) {
            redisTemplate.delete(USER_LOGIN_KEY + username);
            return;
        }
        throw new ClientException("用户未登录或者无Token");
    }
}
